<script>
import {
  getShowImage,
  showToast,
  throttle,
  valIsEmpty,
} from "../../../../../utils";
import dateUtils from "../../../../../utils/dateUtils";
let innerAudioContext = null;
export default {
  name: "audioProcessBar",
  computed: {
    //当前音频切片的开始时间
    currentSliceStartTime() {
      return (
        this.hearingTopicList[this.audio.currentSliceIndex] &&
        this.hearingTopicList[this.audio.currentSliceIndex]
          .audioShardingStartTime
      );
    },
    //当前音频切片的结束时间
    currentSliceEndTime() {
      return (
        this.hearingTopicList[this.audio.currentSliceIndex] &&
        this.hearingTopicList[this.audio.currentSliceIndex].audioShardingEndTime
      );
    },
    //当前切片的持续时长
    currentSliceDuration() {
      return this.currentSliceEndTime - this.currentSliceStartTime;
    },
  },
  props: {
    hearingTopicList: {
      type: Array,
      default: [],
    },
    viewAnalysis: {
      type: Boolean,
      default: false,
    },
    pause: {
      type: Boolean,
      default: true,
    },
    //音频是否加载中
    loading: {
      type: Boolean,
      default: false,
    },
    audioSrc: {
      type: String,
      default: "",
    },
    //播放速率
    playSpeedRate: {
      type: Number,
      default: 1,
    },
  },
  watch: {
    audioSrc: {
      handler(newVal, oldVal) {
        if (newVal) {
          if (!innerAudioContext) this.init();
          innerAudioContext.src = getShowImage(newVal);
        }
      },
      immediate: true,
    },
    hearingTopicList: {
      handler(newVal, oldVal) {
        this.hearingTopicListRender = newVal.map((item) => {
          return {
            ...item,
            audioProcessPercent: "width:0%",
          };
        });
      },
      immediate: true,
    },
    playSpeedRate: {
      handler(newVal) {
        if (!innerAudioContext) this.init();
        if (newVal) innerAudioContext.playbackRate = newVal;
      },
      immediate: true,
    },
    viewAnalysis() {
      //音频进度重置
      this.stopPlay();
    },
  },
  data() {
    return {
      audio: {
        duration: 0, //总时间
        currentTime: 0, //已过时间
        currentSliceIndex: -1, //当前分片索引
      },
      dateUtils,
      hearingTopicListRender: [],
    };
  },
  methods: {
    init() {
      //初始化音频
      innerAudioContext = uni.createInnerAudioContext();
      //监听音频播放进度
      innerAudioContext.onTimeUpdate(() => {
        if (!innerAudioContext) return;
        this.audio.currentTime = innerAudioContext.currentTime;
        this.audio.duration = innerAudioContext.duration;
        //计算当前切片的进度
        const currentSlicePercent = Math.floor(
          ((innerAudioContext.currentTime - this.currentSliceStartTime) /
            this.currentSliceDuration) *
            100,
        );
        //设置播放进度更新到视图上
        if (this.audio.currentSliceIndex !== -1) {
          this.hearingTopicListRender[
            this.audio.currentSliceIndex
          ].audioProcessPercent = `width: ${currentSlicePercent}%;`;
        }
        //判断当前分片是否结束
        if (currentSlicePercent >= 100) {
          //切换到下一个分片
          if (
            this.audio.currentSliceIndex <
            this.hearingTopicListRender.length - 1
          ) {
            this.audio.currentSliceIndex++;
          }
          //如果是解题模式自动切换到相应的题目
          if (!this.viewAnalysis) {
            this.$emit(
              "update:currentQuestionIndex",
              this.audio.currentSliceIndex,
            );
          }
        }
      });
      innerAudioContext.onError((error) => {
        showToast.error("播放失败");
        console.log(error, "error");
      });
      innerAudioContext.onCanplay(() => {
        // if (!this.pause) innerAudioContext.play() //为了解决 onTimeUpdate 钩子不执行的问题
        //获取音频时长
        this.audio.duration =
          this.hearingTopicListRender[
            this.hearingTopicListRender.length - 1
          ].audioShardingEndTime;
      });
      //音频加载中
      innerAudioContext.onWaiting(() => {
        console.log("onWaiting");
        innerAudioContext.pause(); //解决 onTimeUpdate 钩子不执行的问题
        this.$emit("update:loading", true);
      });
      //音频加载完成
      innerAudioContext.offWaiting(() => {
        console.log("offWaiting");
        if (!this.pause) innerAudioContext.play(); //为了解决 onTimeUpdate 钩子不执行的问题
        this.$emit("update:loading", false);
      });
      //播放结束
      innerAudioContext.onEnded(() => {
        this.resetPlay();
      });
    },
    //切换音频分片
    switchSlice(sliceIndex) {
      if (sliceIndex === this.audio.currentSliceIndex) {
        return;
      }
      this.audio.currentSliceIndex = sliceIndex;
      //将先前的音频进度设置为100%
      for (let i = 0; i < sliceIndex; i++) {
        this.hearingTopicListRender[i].audioProcessPercent = "width:100%";
      }
      //将往后的进度设置为0%
      for (let i = sliceIndex; i < this.hearingTopicListRender.length; i++) {
        this.hearingTopicListRender[i].audioProcessPercent = "width:0%";
      }
      //设置播放进度
      // innerAudioContext.pause() //为了解决 onTimeUpdate 钩子不执行的问题
      innerAudioContext.seek(
        this.hearingTopicListRender[sliceIndex].audioShardingStartTime,
      );
      this.audio.currentTime =
        this.hearingTopicListRender[sliceIndex].audioShardingStartTime;
    },
    //播放
    play() {
      //首次播放
      if (this.audio.currentSliceIndex === -1) {
        this.audio.currentSliceIndex = 0;
      }
      innerAudioContext.play();
      this.$emit("update:pause", false);
    },
    //暂停
    handlePause() {
      innerAudioContext.pause();
      this.$emit("update:pause", true);
    },
    //停止播放
    stopPlay() {
      innerAudioContext.stop();
      this.resetPlay();
      this.$emit("update:pause", true);
    },
    //重置播放进度
    resetPlay() {
      this.audio.currentTime = 0;
      this.audio.currentSliceIndex = -1;
      this.$emit("update:pause", true);
      innerAudioContext.seek(0);
      //重置各分片的播放进度
      if (this.hearingTopicListRender) {
        for (let item of this.hearingTopicListRender) {
          item.audioProcessPercent = "";
        }
      }
    },
  },
  //组件被销毁时销毁音频实例
  beforeDestroy() {
    innerAudioContext.destroy();
    innerAudioContext = null;
  },
  //页面隐藏时自动暂停音频
  onPageHide() {
    this.handlePause();
  },
  emits: [
    "update:pause",
    "update:currentQuestionIndex",
    "update:loading",
    "handleSpeedRateModify",
  ],
};
</script>

<template>
  <view class="process-container">
    <!--			音频进度条-->
    <view class="process-bar-list">
      <view
        v-for="(item, index) in hearingTopicListRender"
        :key="item.questionId"
        :style="
          'flex-grow:' +
          (item.audioShardingEndTime - item.audioShardingStartTime)
        "
        :class="[
          'process-bar',
          index === audio.currentSliceIndex ? 'active' : '',
        ]"
      >
        <view class="process-content" :style="item.audioProcessPercent"></view>
      </view>
    </view>
    <view class="footer">
      <!--			播放倍速-->
      <view class="play-speed-rate" @click="$emit('handleSpeedRateModify')">
        <text>当前倍速：</text>
        <text>{{ playSpeedRate }}</text>
      </view>
      <!--				已过时间 / 剩余时间-->
      <view class="process-time">
        {{ dateUtils.formatTime(audio.currentTime) }} /
        {{ dateUtils.formatTime(audio.duration) }}
      </view>
    </view>
  </view>
</template>

<style scoped lang="scss">
.process-container {
  padding: {
    top: 20rpx;
    left: 20rpx;
    right: 20rpx;
  }
  .process-bar-list {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    .process-bar {
      width: 0;
      height: 16rpx;
      background: #dadada;
      position: relative;
      overflow: hidden;
      &:not(:last-child) {
        margin-right: 6rpx;
      }
      &.active {
        height: 26rpx;
      }
      .process-content {
        position: absolute;
        top: 0;
        left: 0;
        height: 100%;
        width: 0;
        background: var(--text-color-theme);
      }
    }
  }
  .footer {
    padding: 20rpx 0;
    display: flex;
    justify-content: space-between;
    .play-speed-rate {
      color: var(--text-color-theme);
    }
  }
}
</style>
